package com.hengyue.controller.system;

import com.hengyue.annotation.Log;
import com.hengyue.common.core.page.TableDataInfo;
import com.hengyue.common.core.result.AjaxResult;
import com.hengyue.common.util.poi.ExcelUtil;
import com.hengyue.common.utils.StringUtils;
import com.hengyue.controller.base.BaseController;
import com.hengyue.enums.BusinessType;
import com.hengyue.security.utils.SecurityUtils;
import com.hengyue.system.domain.criteria.SysUserCriteria;
import com.hengyue.system.domain.entity.SysDept;
import com.hengyue.system.domain.entity.SysRole;
import com.hengyue.system.domain.entity.SysUser;
import com.hengyue.system.domain.vo.SysUserListVO;
import com.hengyue.system.mapstruct.mapper.SysUserVOMapper;
import com.hengyue.system.repository.UserRepository;
import com.hengyue.system.service.ISysDeptService;
import com.hengyue.system.service.ISysPostService;
import com.hengyue.system.service.ISysRoleService;
import com.hengyue.system.service.ISysUserService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.util.Comparator;
import java.util.List;


/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    private final ISysUserService userService;


    private final ISysRoleService roleService;


    private final ISysDeptService deptService;


    private final ISysPostService postService;

    private final SysUserVOMapper sysUserVOMapper;
    private final UserRepository userRepository;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    //@Transactional(readOnly = true)
    public TableDataInfo list(SysUserCriteria criteria) {
        Pageable pageable = getPageable();
        Page<SysUser> page = userService.selectUserPageList(criteria, pageable);
        List<SysUserListVO> userListVOList = sysUserVOMapper.toDto(page.getContent());
        return getDataTable(userListVOList, page.getTotalElements());

    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/{userId}"})
    public AjaxResult getInfo(@NotNull @PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser sysUser = userService.selectUserById(userId);
        sysUser.setPassword(null);
        ajax.put(AjaxResult.DATA_TAG, sysUser);
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (userService.isUserNameNotUnique(user.getName(), user.getId())) {
            return error("新增用户'" + user.getName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhoneNumber()) && userService.isPhoneNotUnique(user.getPhoneNumber(), user.getId())) {
            return error("新增用户'" + user.getName() + "'失败，手机号码已存在");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        userService.insertUser(user);
        return success();
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        if (userService.isUserNameNotUnique(user.getName(), user.getId())) {
            return error("修改用户'" + user.getName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhoneNumber()) && userService.isPhoneNotUnique(user.getPhoneNumber(), user.getId())) {
            return error("修改用户'" + user.getName() + "'失败，手机号码已存在");
        }
        userService.updateUser(user);
        return success();
    }



    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        userService.deleteUserByIds(userIds);
        return success();
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        SysUser currentUser = userRepository.findById(user.getId()).orElseThrow(() -> new RuntimeException("用户不存在"));
        currentUser.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        userRepository.save(currentUser);
        return success();
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        //userService.checkUserAllowed(user);
        userService.updateUserStatus(user);
        return success();
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    @Transactional(readOnly = true)
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        SysRole role = new SysRole();
        List<SysRole> roles = user.getSysRoles().stream().sorted(Comparator.comparingInt(SysRole::getRoleSort)).toList();
        ajax.put("user", user);
        //ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("roles", roles);
        return ajax;
    }


    @GetMapping("/unAuthRole/{userId}")
    @Transactional(readOnly = true)
    public AjaxResult getUnAuthRole(@NotNull @PathVariable("userId") Long userId) {
        return AjaxResult.success(roleService.selectUnassignedRolesByUserId(userId));
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult updateAuthRole(Long userId, Long[] roleIds) {
        /*userService.checkUserDataScope(userId);
        roleService.checkRoleDataScope(roleIds);*/

        userService.updateUserAuth(userId, roleIds);
        return success();
    }

    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @DeleteMapping("/delAuthRole")
    public AjaxResult deleteAuthRole(Long userId, Long[] roleIds) {
        userService.deleteUserAuth(userId, roleIds);
        return success();
    }


    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }
}
